package cn.com.open.itembank.controller;

import cn.com.open.itembank.common.GlobalConst;
import cn.com.open.itembank.dto.ChapterInputModel;
import cn.com.open.itembank.dto.ReturnModel;
import cn.com.open.itembank.entity.Chapter;
import cn.com.open.itembank.interceptor.Log;
import cn.com.open.itembank.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by lucky on 2017/7/13.
 */

/**
 * 章节控制器
 */
@RestController
@RequestMapping("/itembank")
public class ChapterController extends BaseController {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ChapterController.class);

    public static String appKeyString = "appkey";
    public static String appSecretString = "appsecret";
    @Autowired
    private ChapterService service;

    //region 新增相关（Create：理论方法 HttpPost）

    /**
     * 新增章节
     *
     * @param request
     * @param response
     * @param itembankId
     * @param chapter
     */
    @Log(optType = "新增章节", optDescription = "新增章节，根据%s", keyName = "")
    @PostMapping(value = "/{itembankId}/chapter")
    public void insert(HttpServletRequest request, HttpServletResponse response,
                       @PathVariable(value = "itembankId") String itembankId,
                       @RequestBody Chapter chapter) {

        ReturnModel result = service.insert(itembankId,chapter);

        if (result.getCode() == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.COURSE_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }
    }


    //endregion

    //region 删除相关（Delete：理论方法 HttpDelete）

    /**
     * 删除题库下全部章节信息.
     *
     * @param itembankId
     * @return
     */
    @Log(optType = "删除题库下全部章节信息", optDescription = "删除题库下全部章节信息.，根据题库id%s", keyName = "itembankId")
    @DeleteMapping(value = "/{itembankId}/chapter")
    public void deleteByItemBankId(HttpServletRequest request, HttpServletResponse response,
                                   @PathVariable("itembankId") String itembankId) {
        ReturnModel result = service.deleteByItemBankId(itembankId);

        if (result.getCode() < 0) {
            responseJson(request, response, result, "");
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    /**
     * 根据章节ID删除章节信息
     *
     * @param itembankId
     * @return
     */
    @Log(optType = "根据章节ID删除章节信息", optDescription = "根据章节ID%s删除章节信息", keyName = "chapterId")
    @DeleteMapping(value = "/{itembankId}/chapter/{chapterId}/deletechapter")
    public void deleteById(HttpServletRequest request, HttpServletResponse response,
                           @PathVariable("itembankId") String itembankId,
                           @PathVariable("chapterId") String chapterId) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.deleteById(appKey, itembankId, chapterId);

        if (result.getCode() == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.DATA_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else if (result.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }

    /**
     * 根据子章节ID删除章节信息
     *
     * @param itembankId
     * @return
     */
    @Log(optType = "根据子章节ID删除章节信息", optDescription = "根据子章节ID%s删除章节信息", keyName = "chapterId")
    @DeleteMapping(value = "/{itembankId}/chapter/{chapterId}")
    public void deleteByChildId(HttpServletRequest request, HttpServletResponse response,
                                @PathVariable("itembankId") String itembankId,
                                @PathVariable("chapters") String chapters,
                                @PathVariable("chapterId") String chapterId) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.deleteByChildId(appKey, itembankId, chapters, chapterId);

        if (result.getCode() == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.DATA_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else if (result.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }


    //endregion

    //region 更新相关（Update：理论方法 HttpPut）

    /**
     * 修改章节名称.
     *
     * @param chapterId
     * @param chapter
     * @return
     */
    @Log(optType = "修改章节名称", optDescription = "修改章节名称根据章节id%s", keyName = "chapterId")
    @PutMapping(value = "/{itembankId}/chapter/{chapterId}")
    public void updateChapterName(HttpServletRequest request, HttpServletResponse response,
                       @PathVariable("itembankId") String itembankId,
                       @PathVariable("chapterId") String chapterId,
                       @RequestBody Chapter chapter) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.updateChapterName(appKey,itembankId,chapterId, chapter.getChapterName());

        if (result.getCode() == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.COURSE_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }

    }

    /**
     * 拖拽更新章节
     *
     * @param itembankId
     * @param chapterId
     * @param parentId
     * @param type
     * @return
     */
    @Log(optType = "拖拽更新章节", optDescription = "拖拽更新章节%s", keyName = "chapterId")
    @PutMapping(value = "/{itembankId}/chapter/{chapterId}/drag")
    public void updateChapter(HttpServletRequest request, HttpServletResponse response,
                              @PathVariable("itembankId") String itembankId,
                              @PathVariable("chapterId") String chapterId,
                              @RequestParam("parentId") String parentId,
                              @RequestParam("type") Integer type) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.updateChapter(appKey, itembankId, chapterId, parentId, type);
        if (result.getCode() == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.COURSE_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, "", "", result.getCode());
        }
    }

    /**
     * 拖拽后数据同步
     *
     * @param itembankId
     * @param chapterInputModel
     * @return
     */
    @Log(optType = "拖拽后数据同步", optDescription = "拖拽后数据同步%s", keyName = "jsonString")
    @PutMapping(value = "/{itembankId}/chapter/dragchapter")
    public void dragChapter(HttpServletRequest request, HttpServletResponse response,
                            @PathVariable("itembankId") String itembankId,
                            @RequestBody ChapterInputModel chapterInputModel) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.dragChapter(appKey, itembankId, chapterInputModel);
        if (result.getCode() == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.COURSE_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, "", "", result.getCode());
        }
    }

    //endregion

    //region 查询相关（Retrieve：理论方法 HttpGet）

    /**
     * 获取章节信息
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId the itembankId
     * @param chapterId  the chapterId
     */
    @Log(optType = "获取章节信息", optDescription = "获取章节信息，根据%s", keyName = "")
    @GetMapping(value = "/{itembankId}/chapter/{chapterId}")
    public void getChapterInfo(HttpServletRequest request, HttpServletResponse response,
                               @PathVariable(value = "itembankId") String itembankId,
                               @PathVariable(value = "chapterId") String chapterId) {

        Chapter result = service.getChapterInfo(itembankId, chapterId);
        if (result != null) {
            responseJson(request, response, result, "");
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    /**
     * 获取课程全部章节
     *
     * @param itembankId itembankId
     * @return 可用题库列表
     */
    @Log(optType = "获取课程全部章节", optDescription = "获取课程全部章节，根据%s", keyName = "itembankId")
    @GetMapping(value = "/{itembankId}/chapterlist")
    public void getCourseChapter(HttpServletRequest request, HttpServletResponse response,
                                 @PathVariable("itembankId") String itembankId) {
        String appKey = request.getHeader(appKeyString);

        ReturnModel result = service.getCourseChapter(appKey, itembankId);
        if (result.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }

    }

    /**
     * 获取课程题库下所有章节列表(树)
     *
     * @param itembankId itembankId
     * @return 可用题库列表
     */
    @Log(optType = "获取课程题库下所有章节列表树", optDescription = "获取课程题库下所有章节列表树，根据%s", keyName = "itembankId")
    @GetMapping(value = "/{itembankId}/chaptertree")
    public void getAllChaptList(HttpServletRequest request, HttpServletResponse response,
                                @PathVariable("itembankId") String itembankId) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.getAllChaptList(appKey, itembankId);
        if (result.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }
    }

    /**
     * 获取章节（策略用）
     *
     * @param itembankId itembankId
     * @return 可用题库列表
     */
    @Log(optType = "获取章节（策略用）", optDescription = "获取章节（策略用），根据%s", keyName = "")
    @GetMapping(value = "/{itembankId}/getchildchapterbyguid")
    public void getChaptForRules(HttpServletRequest request, HttpServletResponse response,
                                 @PathVariable("itembankId") String itembankId,
                                 @PathVariable("firstChapterId") String firstChapterId,
                                 @PathVariable("lastChapterId") String lastChapterId) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.getChaptForRules(appKey, itembankId, firstChapterId, lastChapterId);
        if (result.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }
    }

    /**
     * 获取章节（策略修改用）
     *
     * @param itembankId itembankId
     * @return 可用题库列表
     */
    @Log(optType = "获取章节（策略修改用）", optDescription = "获取章节（策略修改用），根据%s", keyName = "")
    @GetMapping(value = "/{itembankId}/getcheckchapterbyguid")
    public void getChaptForUpdateRules(HttpServletRequest request, HttpServletResponse response,
                                       @PathVariable("itembankId") String itembankId,
                                       @PathVariable("chapterId") String chapterId) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.getChaptForUpdateRules(appKey, itembankId, chapterId);
        if (result.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }
    }


    /**
     * 获取章节(根据章节集合和章节id串)
     *
     * @param itembankId itembankId
     * @param chapter    chapter
     * @return 可用题库列表
     */
    @Log(optType = "获取章节(根据章节集合和章节id串)", optDescription = "获取章节(根据章节集合和章节id串)，根据%s", keyName = "")
    @GetMapping(value = "/{itembankId}/chapter/{chapterId}/getlist")
    public void getChildModel(HttpServletRequest request, HttpServletResponse response,
                              @PathVariable("itembankId") String itembankId,
                              @RequestBody List<Chapter> chapter,
                              @PathVariable("chapterId") String chapterId) {
        String appKey = request.getHeader(appKeyString);
        ReturnModel result = service.getChildModel(appKey, itembankId, chapter, chapterId);
        if (result.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }
    }

    //endregion
}
